//
//  Task+Extension.swift
//  LiveTrivia
//
//  Created by Gesen on 2017/12/9.
//  Copyright © 2017年 LiveTrivia. All rights reserved.
//

import Moya
import Alamofire

extension Task {
    
    static func json(_ parameters: [String: Any]) -> Task {
        print("parameters = \(parameters)")
        return .requestParameters(
            parameters: parameters,
            encoding: URLEncoding.default
        )
    }
    
    static func jsonArray(_ parameters: [Any]) -> Task {
        return .requestParameters(
            parameters: ["jsonArray": parameters],
            encoding: JSONArrayEncoding.default
        )
    }
    
}

struct JSONArrayEncoding: Alamofire.ParameterEncoding {

    static let `default` = JSONArrayEncoding()

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        guard let json = parameters?["jsonArray"] else { return request }
        let data = try JSONSerialization.data(withJSONObject: json, options: [])
        if request.value(forHTTPHeaderField: "Content-Type") == nil {
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }
        request.httpBody = data
        return request
    }
    
}
